package org.jsonstruts.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsonstruts.exception.NoFoundBeanInSpringConfigurationException;
import org.jsonstruts.spring.ApplicationSupport;
import org.jsonstruts.utils.HttpUtils;

public class DispatcherFilter implements Filter {
	Log logger = LogFactory.getLog(DispatcherFilter.class);
	private Map<String, String> mapping;
	 

	@Override
	public void destroy() {
		mapping = null;
	}

	 
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpUtils httpUtils = HttpUtils.getInstance();
		httpUtils.setRequest(request);
		httpUtils.setResponse((HttpServletResponse) resp);
		httpUtils.setSession(request.getSession());
		httpUtils.setContext(request.getSession().getServletContext());
		String url = request.getRequestURI();
		String path = request.getContextPath();
		String key = url.replace(path, "");
		if (mapping.containsKey(key))
			try {
				Execute.handle(request, mapping.get(key), (HttpServletResponse) resp);
			} catch (NoFoundBeanInSpringConfigurationException e) {
				chain.doFilter(request, resp);
				e.printStackTrace();
			}
		else
			chain.doFilter(request, resp);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		logger.info("Init DispatcherFilter...");
		Dispatcher dispatcher = Dispatcher.getDispatcher();
		mapping = dispatcher.InitMappingList();
		boolean enabled = isSpringEnabled(config);
		if (enabled == true) {
			logger.info("Loading Spring module...");
			ApplicationSupport.Init(config.getServletContext());
		} else {
			logger.info("'isEnableSpring' not be setted to 'true',Spring module shutdown...");
		}

	}

	public boolean isSpringEnabled(FilterConfig config) {
		String isEnableSpring = config.getInitParameter("isEnableSpring");
		if (isEnableSpring != null)
			return isEnableSpring.toLowerCase().trim().equals("true");
		else
			return false;

	}

}
